package com.evaluation.kexingcp.psycho.evaluation.sys.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.kexingcp.admin.api.entity.SysRole;
import com.evaluation.kexingcp.admin.api.entity.SysTenant;
import com.evaluation.kexingcp.admin.service.SysRoleService;
import com.evaluation.kexingcp.admin.service.SysTenantService;
import com.evaluation.kexingcp.common.core.constant.CacheConstants;
import com.evaluation.kexingcp.common.core.constant.enums.LoginTypeEnum;
import com.evaluation.kexingcp.common.core.util.R;
import com.evaluation.kexingcp.common.data.tenant.TenantBroker;
import com.evaluation.kexingcp.common.data.tenant.TenantContextHolder;
import com.evaluation.kexingcp.common.excel.annotation.ResponseExcel;
import com.evaluation.kexingcp.common.log.annotation.SysLog;
import com.evaluation.kexingcp.common.security.annotation.Inner;
import com.evaluation.kexingcp.common.security.service.KexingcpUser;
import com.evaluation.kexingcp.common.security.util.SecurityUtils;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.CompanyAppEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationSalesmanEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationTenantTypesEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.CompanyAppService;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationSalesmanService;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationTenantTypesService;
import com.evaluation.kexingcp.psycho.evaluation.sys.sms.SmsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * 公司申请表
 *
 * @author kexingcp
 * @date 2024-10-29 09:13:00
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/companyApp" )
@Tag(description = "companyApp" , name = "公司申请表管理" )
public class CompanyAppController {

    private final CompanyAppService companyAppService;
    private final StringRedisTemplate redisTemplate;
    private final EvaluationTenantTypesService tenantTypesService;
    private final SysTenantService sysTenantService;
    private final SmsService smsService;
    private final EvaluationSalesmanService salesmanService;
    private final SysRoleService sysRoleService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param companyApp 公司申请表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('admin_companyApp_view')" )
    public R getCompanyAppPage(@ParameterObject Page page, @ParameterObject CompanyAppEntity companyApp) {
        LambdaQueryWrapper<CompanyAppEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(companyApp.getSalesmanName()), CompanyAppEntity::getSalesmanName, companyApp.getSalesmanName());

        KexingcpUser user = SecurityUtils.getUser();
        List<String> roles = sysRoleService.findRolesByUserId(SecurityUtils.getUser().getId()).stream().map(SysRole::getRoleCode).toList();
        if (roles.contains("XS_USER")) {
            // 找到自己的推广码
            EvaluationSalesmanEntity salesmanEntity = salesmanService.getOne(Wrappers.lambdaQuery(EvaluationSalesmanEntity.class).eq(EvaluationSalesmanEntity::getSalesmanName, user.getName()));
            wrapper.eq(CompanyAppEntity::getSalesmanCode, salesmanEntity.getSalesmanCode());
        }

        return R.ok(companyAppService.page(page, wrapper));
    }


    /**
     * 通过id查询公司申请表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('admin_companyApp_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(companyAppService.getById(id));
    }

    /**
     * 新增公司申请表
     * @param appEntity 公司申请表
     * @return R
     */
    @Operation(summary = "新增公司申请表" , description = "新增公司申请表" )
    @SysLog("新增公司申请表" )
    @PostMapping
    @Inner(value = false)
    @Transactional
    public R save(@RequestBody CompanyAppEntity appEntity) {

        String cacheKey = CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.REG.getType() + StringPool.AT + appEntity.getMobile();
        String codeObj = redisTemplate.opsForValue().get(cacheKey);

        if (StrUtil.isEmpty(codeObj)) {
            return R.failed(Boolean.FALSE, "验证码失效");
        }

        if (!Objects.equals(codeObj, appEntity.getCode())) {
            return R.failed(Boolean.FALSE, "验证码错误");
        }

        if (StringUtils.isNotEmpty(appEntity.getSalesmanCode())) {
            EvaluationSalesmanEntity salesmanEntity = salesmanService.getOne(Wrappers.lambdaQuery(EvaluationSalesmanEntity.class).eq(EvaluationSalesmanEntity::getSalesmanCode, appEntity.getSalesmanCode()), false);
            if (salesmanEntity != null) {
                appEntity.setSalesmanName(salesmanEntity.getSalesmanName());
            }
        }

        EvaluationTenantTypesEntity tenantTypesEntity =  tenantTypesService.getOne(Wrappers.lambdaQuery(EvaluationTenantTypesEntity.class).eq(EvaluationTenantTypesEntity::getName, appEntity.getVersions()));

        SysTenant tenant = new SysTenant();
        String randomStr = RandomUtil.randomString(6).toLowerCase(Locale.getDefault());
        tenant.setName(appEntity.getCompanyName());
        tenant.setCode(randomStr);
        tenant.setMenuId(tenantTypesEntity.getMenus());
        tenant.setStatus("0");
        tenant.setMobile(appEntity.getMobile());
        tenant.setOrgType(appEntity.getVersions());
        tenant.setEmail(appEntity.getEmail());
        tenant.setUserFields(tenantTypesEntity.getUserFileds());
        tenant.setScales(tenantTypesEntity.getScales());
        tenant.setStartTime(LocalDateTime.now());
        tenant.setEndTime(LocalDateTime.of(2025,10,30, 0, 0, 0));
        tenant.setAccount(appEntity.getAccount());
        tenant.setPassword(appEntity.getPassword());
        tenant.setCreateBy(appEntity.getAccount());
        tenant.setUpdateBy(appEntity.getAccount());

        sysTenantService.save(tenant);

        TenantContextHolder.setUserName(appEntity.getAccount());
        TenantBroker.runAs(tenant.getId(), tenantId -> {
            sysTenantService.saveTenant(tenant);
        });

        return R.ok(companyAppService.save(appEntity));
    }

    /**
     * 修改公司申请表
     * @param companyApp 公司申请表
     * @return R
     */
    @Operation(summary = "修改公司申请表" , description = "修改公司申请表" )
    @SysLog("修改公司申请表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin_companyApp_edit')" )
    public R updateById(@RequestBody CompanyAppEntity companyApp) {

//        if (companyApp.getApproved()) {
//            CompanyAppEntity appEntity = companyAppService.getById(companyApp.getId());
//            EvaluationTenantTypesEntity tenantTypesEntity =  tenantTypesService.getOne(Wrappers.lambdaQuery(EvaluationTenantTypesEntity.class).eq(EvaluationTenantTypesEntity::getName, appEntity.getVersions()));
//
//            SysTenant tenant = new SysTenant();
//            String randomStr = RandomUtil.randomString(6).toLowerCase(Locale.getDefault());
//
//            tenant.setName(appEntity.getCompanyName());
//            tenant.setCode(randomStr);
//            tenant.setMenuId(tenantTypesEntity.getMenus());
//            tenant.setStatus("0");
//            tenant.setMobile(appEntity.getMobile());
//            tenant.setOrgType(appEntity.getVersions());
//            tenant.setEmail(appEntity.getEmail());
//            tenant.setUserFields(tenantTypesEntity.getUserFileds());
//            tenant.setScales(tenantTypesEntity.getScales());
//            tenant.setStartTime(LocalDateTime.now());
//            tenant.setEndTime(LocalDateTime.of(2025,10,30, 0, 0, 0));
//            tenant.setAccount(companyApp.getAccount());
//            tenant.setPassword(appEntity.getPassword());
//
//            sysTenantService.saveTenant(tenant);
//
//            //smsService.sendRegisterEmail(companyApp.getEmail(), appEntity.getCompanyName(), appEntity.getAccount(), randomStr + ".sxkx.cn", appEntity.getPassword());
//        }

        return R.ok(companyAppService.updateById(companyApp));
    }

    /**
     * 通过id删除公司申请表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除公司申请表" , description = "通过id删除公司申请表" )
    @SysLog("通过id删除公司申请表" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('admin_companyApp_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(companyAppService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param companyApp 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('admin_companyApp_export')" )
    public List<CompanyAppEntity> export(CompanyAppEntity companyApp,Long[] ids) {
        return companyAppService.list(Wrappers.lambdaQuery(companyApp).in(ArrayUtil.isNotEmpty(ids), CompanyAppEntity::getId, ids));
    }
}